use std::fs::{self};

use crate::utils::{execute_tool, get_os_type, OsType};

pub fn get_hdc_name() -> String {
    match get_os_type() {
        OsType::Windows => "hdc.exe".to_string(),
        OsType::Mac | OsType::Linux | OsType::Unknown => "hdc".to_string(),
    }
}

pub fn get_hilog_name() -> String {
    match get_os_type() {
        OsType::Windows => "hilog.exe".to_string(),
        OsType::Mac | OsType::Linux | OsType::Unknown => "hilog".to_string(),
    }
}

pub fn get_device() -> Result<String, Box<dyn std::error::Error>> {
    let args = ["list", "targets"];
    let result = execute_tool(&get_hdc_name(), &args)?;
    if result.is_single_line_and_not_empty() {
        Ok(result.stdout.trim().to_string())
    }  else {
        Err(format!("Cannot find device: {}", result.stderr).into())
    }
}

pub fn get_hilog(
    save_path: &String,
    start_time: Option<&str>,
    end_time: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    println!("pull device hilog ...");
    let args = ["file", "recv", "/data/log/hilog", &save_path];
    let _ = execute_tool(&get_hdc_name(), &args)?;
    println!("pull device hilog success!");

    println!("filter hilog files ...");
    let entries = fs::read_dir(format!("{}/{}", &save_path, "hilog"))?;
    for entry in entries {
        let entry = entry?;
        let path = entry.path();
        if path.is_file() {
            if let Some(file_name) = path.file_name().and_then(|s| s.to_str()) {
                if file_name.starts_with("hilog.") && file_name.ends_with(".gz") {
                    if let Some(date) = extract_date_from_filename(file_name) {
                        let file_date_mmdd = &date[4..8];
                        let file_date_mmdd = format!("{}-{}", &file_date_mmdd[0..2], &file_date_mmdd[2..4]);
                        let within_range = match (start_time, end_time) {
                            (Some(start), Some(end)) => {
                                file_date_mmdd.as_str() >= start && file_date_mmdd.as_str() <= end
                            }
                            (Some(start), None) => file_date_mmdd.as_str() >= start,
                            (None, Some(end)) => file_date_mmdd.as_str() <= end,
                            (None, None) => true
                        };
                        if !within_range {
                            // 删除不符合的文件
                            fs::remove_file(&path)?;
                        }
                    }
                }
            }
        }
    }
    println!("filter hilog files success!");

    println!("parse device hilog ...");
    let args = ["parse", "-i", &save_path, "-d", &save_path, "-o", &save_path];
    let _ = execute_tool(&get_hilog_name(), &args)?;
    println!("parse device hilog success!");

    Ok(())
}

pub fn extract_date_from_filename(file_name: &str) -> Option<&str> {
    let parts: Vec<&str> = file_name.split('.').collect();
    if parts.len() >= 3 {
        let date_part = parts[2];
        let date = date_part.split('-').next()?;
        Some(date)
    } else {
        None
    }
}